<?php
/**
 * logs.inc
 * View the different system logs.
 * @copyright	Copyright(c) 2002-2010 Bjorn Winberg
 * @author		Bjorn Winberg <cms@anomalye.net>
 * @license		http://www.gnu.org/licenses/gpl.html GNU General Public License version 2
 * @package		AnomalyWiki
 */
class Logs extends Module{
	public static $MODULE_UID = 'logs';
	const PARAM_MAX_MODULE = 64;
	protected $mSystem;	
	
	/**
	 *
	 */
	public function __construct(){
		parent::__construct();
		$this->loadSettings();
		$this->mSystem = ModuleFactory::loadModule('system');	
	}
	
	/**
	 *
	 */
	public function generateView(){
		if(!$this->requireAuthorization('LOGS/READ')){
			$this->mSystem->feedbackWarn($this->mSystem->localString('ERROR_PERMISSION_DENIED'));
			return false;
		}
		$inputModule = $this->getParamEnc('module', 1, self::PARAM_MAX_MODULE);
		$params = array();
		$params['list'] = array();
		$db = ModuleFactory::getDb();
		
		$modulesResult = $db->dbQuery('SELECT DISTINCT module FROM system_log');
		while($row = $modulesResult->fetchArray(SQLITE3_ASSOC)){ 
			$params['modules'][$row['module']] = ModuleFactory::getString($row['module'], 'MODULE_NAME');
		}
		
		$sqlPageSize = $this->localSetting('LOGS_PAGE_SIZE') + 1;
		if($inputModule !== false){
			$listResult = $db->dbQuery('SELECT * FROM system_log LEFT OUTER JOIN auth_user ON auth_user.id=system_log.user_id WHERE module=\'' . $db->dbEscape($inputModule) . '\' ORDER BY timestamp DESC LIMIT ' . $db->dbEscape($sqlPageSize) . ' OFFSET ' . $db->dbEscape($this->pagingOffset()));
			$logsBaseUrl = $this->generateUrl('logs', array('module' => $inputModule));
		}
		else{
			$listResult = $db->dbQuery('SELECT * FROM system_log LEFT OUTER JOIN auth_user ON auth_user.id=system_log.user_id ORDER BY timestamp DESC LIMIT ' . $db->dbEscape($sqlPageSize) . ' OFFSET ' . $db->dbEscape($this->pagingOffset()));
			$logsBaseUrl = $this->generateUrl('logs');
		}
		$selectCount = 0;
		while($row = $listResult->fetchArray(SQLITE3_ASSOC)){ 
			if($selectCount < $this->localSetting('LOGS_PAGE_SIZE')){
				$params['list'][$selectCount]['time'] = $row['timestamp'];
				$params['list'][$selectCount]['module'] = $row['module'];
				$params['list'][$selectCount]['user_name'] = $row['name'];
				$params['list'][$selectCount]['user_id'] = $row['user_id'];
				$params['list'][$selectCount]['message'] = $row['message'];
				$selectCount++;
			}
		}
		$params['logsNext'] = $this->pagingNextUrl($logsBaseUrl, $this->localSetting('LOGS_PAGE_SIZE'), $selectCount);
		$params['logsPrev'] = $this->pagingPrevUrl($logsBaseUrl, $this->localSetting('LOGS_PAGE_SIZE'));
		return $this->generateTemplate('logs_list.inc', $params);
	}
	
	/**
	 *
	 */
	public function firstTimeSetup(){
		$db = ModuleFactory::getDb();
		$auth = ModuleFactory::loadModule('auth');
		$readId = $auth->addAction($db, rawurlencode('LOGS/READ'), 1);
		$auth->grantAction($db, $auth::ADMIN_GROUP_ID, $readId);
	}
}
?>
